﻿#region Using directives

using System;
using System.Data;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;

using EAdvice.Entities;
using EAdvice.Data;

#endregion

namespace EAdvice.Data.Bases
{	
	///<summary>
	/// This class is the base class for any <see cref="AfiProviderBase"/> implementation.
	/// It exposes CRUD methods as well as selecting on index, foreign keys and custom stored procedures.
	///</summary>
	public abstract partial class AfiProviderBaseCore : EntityProviderBase<EAdvice.Entities.Afi, EAdvice.Entities.AfiKey>
	{		
		#region Get from Many To Many Relationship Functions
		#endregion	
		
		#region Delete Methods

		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
		/// <param name="key">The unique identifier of the row to delete.</param>
		/// <returns>Returns true if operation suceeded.</returns>
		public override bool Delete(TransactionManager transactionManager, EAdvice.Entities.AfiKey key)
		{
			return Delete(transactionManager, key.AfiCode);
		}
		
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="_afiCode">. Primary Key.</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
		public bool Delete(System.String _afiCode)
		{
			return Delete(null, _afiCode);
		}
		
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_afiCode">. Primary Key.</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
		public abstract bool Delete(TransactionManager transactionManager, System.String _afiCode);		
		
		#endregion Delete Methods
		
		#region Get By Foreign Key Functions
	
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_AFI_WebUser key.
		///		FK_AFI_WebUser Description: 
		/// </summary>
		/// <param name="_createdBy"></param>
		/// <returns>Returns a typed collection of EAdvice.Entities.Afi objects.</returns>
		public TList<Afi> GetByCreatedBy(System.String _createdBy)
		{
			int count = -1;
			return GetByCreatedBy(_createdBy, 0,int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_AFI_WebUser key.
		///		FK_AFI_WebUser Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_createdBy"></param>
		/// <returns>Returns a typed collection of EAdvice.Entities.Afi objects.</returns>
		/// <remarks></remarks>
		public TList<Afi> GetByCreatedBy(TransactionManager transactionManager, System.String _createdBy)
		{
			int count = -1;
			return GetByCreatedBy(transactionManager, _createdBy, 0, int.MaxValue, out count);
		}
		
			/// <summary>
		/// 	Gets rows from the datasource based on the FK_AFI_WebUser key.
		///		FK_AFI_WebUser Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_createdBy"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		///  <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of EAdvice.Entities.Afi objects.</returns>
		public TList<Afi> GetByCreatedBy(TransactionManager transactionManager, System.String _createdBy, int start, int pageLength)
		{
			int count = -1;
			return GetByCreatedBy(transactionManager, _createdBy, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_AFI_WebUser key.
		///		fkAfiWebUser Description: 
		/// </summary>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="_createdBy"></param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of EAdvice.Entities.Afi objects.</returns>
		public TList<Afi> GetByCreatedBy(System.String _createdBy, int start, int pageLength)
		{
			int count =  -1;
			return GetByCreatedBy(null, _createdBy, start, pageLength,out count);	
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_AFI_WebUser key.
		///		fkAfiWebUser Description: 
		/// </summary>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="_createdBy"></param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of EAdvice.Entities.Afi objects.</returns>
		public TList<Afi> GetByCreatedBy(System.String _createdBy, int start, int pageLength,out int count)
		{
			return GetByCreatedBy(null, _createdBy, start, pageLength, out count);	
		}
						
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_AFI_WebUser key.
		///		FK_AFI_WebUser Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_createdBy"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">The total number of records.</param>
		/// <returns>Returns a typed collection of EAdvice.Entities.Afi objects.</returns>
		public abstract TList<Afi> GetByCreatedBy(TransactionManager transactionManager, System.String _createdBy, int start, int pageLength, out int count);
		
		#endregion

		#region Get By Index Functions
		
		/// <summary>
		/// 	Gets a row from the DataSource based on its primary key.
		/// </summary>
		/// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
		/// <param name="key">The unique identifier of the row to retrieve.</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <returns>Returns an instance of the Entity class.</returns>
		public override EAdvice.Entities.Afi Get(TransactionManager transactionManager, EAdvice.Entities.AfiKey key, int start, int pageLength)
		{
			return GetByAfiCode(transactionManager, key.AfiCode, start, pageLength);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the primary key PK_AFI index.
		/// </summary>
		/// <param name="_afiCode"></param>
		/// <returns>Returns an instance of the <see cref="EAdvice.Entities.Afi"/> class.</returns>
		public EAdvice.Entities.Afi GetByAfiCode(System.String _afiCode)
		{
			int count = -1;
			return GetByAfiCode(null,_afiCode, 0, int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_AFI index.
		/// </summary>
		/// <param name="_afiCode"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="EAdvice.Entities.Afi"/> class.</returns>
		public EAdvice.Entities.Afi GetByAfiCode(System.String _afiCode, int start, int pageLength)
		{
			int count = -1;
			return GetByAfiCode(null, _afiCode, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_AFI index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_afiCode"></param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="EAdvice.Entities.Afi"/> class.</returns>
		public EAdvice.Entities.Afi GetByAfiCode(TransactionManager transactionManager, System.String _afiCode)
		{
			int count = -1;
			return GetByAfiCode(transactionManager, _afiCode, 0, int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_AFI index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_afiCode"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="EAdvice.Entities.Afi"/> class.</returns>
		public EAdvice.Entities.Afi GetByAfiCode(TransactionManager transactionManager, System.String _afiCode, int start, int pageLength)
		{
			int count = -1;
			return GetByAfiCode(transactionManager, _afiCode, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_AFI index.
		/// </summary>
		/// <param name="_afiCode"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="EAdvice.Entities.Afi"/> class.</returns>
		public EAdvice.Entities.Afi GetByAfiCode(System.String _afiCode, int start, int pageLength, out int count)
		{
			return GetByAfiCode(null, _afiCode, start, pageLength, out count);
		}
		
				
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_AFI index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_afiCode"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">The total number of records.</param>
		/// <returns>Returns an instance of the <see cref="EAdvice.Entities.Afi"/> class.</returns>
		public abstract EAdvice.Entities.Afi GetByAfiCode(TransactionManager transactionManager, System.String _afiCode, int start, int pageLength, out int count);
						
		#endregion "Get By Index Functions"
	
		#region Custom Methods
		
		
		#endregion

		#region Helper Functions	
		
		/// <summary>
		/// Fill a TList&lt;Afi&gt; From a DataReader.
		/// </summary>
		/// <param name="reader">Datareader</param>
		/// <param name="rows">The collection to fill</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">number of rows.</param>
		/// <returns>a <see cref="TList&lt;Afi&gt;"/></returns>
		public static TList<Afi> Fill(IDataReader reader, TList<Afi> rows, int start, int pageLength)
		{
			NetTiersProvider currentProvider = DataRepository.Provider;
            bool useEntityFactory = currentProvider.UseEntityFactory;
            bool enableEntityTracking = currentProvider.EnableEntityTracking;
            LoadPolicy currentLoadPolicy = currentProvider.CurrentLoadPolicy;
			Type entityCreationFactoryType = currentProvider.EntityCreationalFactoryType;
			
			// advance to the starting row
			for (int i = 0; i < start; i++)
			{
				if (!reader.Read())
				return rows; // not enough rows, just return
			}
			for (int i = 0; i < pageLength; i++)
			{
				if (!reader.Read())
					break; // we are done
					
				string key = null;
				
				EAdvice.Entities.Afi c = null;
				if (useEntityFactory)
				{
					key = new System.Text.StringBuilder("Afi")
					.Append("|").Append((System.String)reader[((int)AfiColumn.AfiCode - 1)]).ToString();
					c = EntityManager.LocateOrCreate<Afi>(
					key.ToString(), // EntityTrackingKey
					"Afi",  //Creational Type
					entityCreationFactoryType,  //Factory used to create entity
					enableEntityTracking); // Track this entity?
				}
				else
				{
					c = new EAdvice.Entities.Afi();
				}
				
				if (!enableEntityTracking ||
					c.EntityState == EntityState.Added ||
					(enableEntityTracking &&
					
						(
							(currentLoadPolicy == LoadPolicy.PreserveChanges && c.EntityState == EntityState.Unchanged) ||
							(currentLoadPolicy == LoadPolicy.DiscardChanges && c.EntityState != EntityState.Unchanged)
						)
					))
				{
					c.SuppressEntityEvents = true;
					c.AfiCode = (System.String)reader[((int)AfiColumn.AfiCode - 1)];
					c.OriginalAfiCode = c.AfiCode;
					c.ClientName = (System.String)reader[((int)AfiColumn.ClientName - 1)];
					c.ClientAddress1 = (reader.IsDBNull(((int)AfiColumn.ClientAddress1 - 1)))?null:(System.String)reader[((int)AfiColumn.ClientAddress1 - 1)];
					c.ClientAddress2 = (reader.IsDBNull(((int)AfiColumn.ClientAddress2 - 1)))?null:(System.String)reader[((int)AfiColumn.ClientAddress2 - 1)];
					c.ClientAddress3 = (reader.IsDBNull(((int)AfiColumn.ClientAddress3 - 1)))?null:(System.String)reader[((int)AfiColumn.ClientAddress3 - 1)];
					c.ClientTaxCode = (reader.IsDBNull(((int)AfiColumn.ClientTaxCode - 1)))?null:(System.String)reader[((int)AfiColumn.ClientTaxCode - 1)];
					c.CreatedBy = (reader.IsDBNull(((int)AfiColumn.CreatedBy - 1)))?null:(System.String)reader[((int)AfiColumn.CreatedBy - 1)];
					c.CreatedDate = (System.DateTime)reader[((int)AfiColumn.CreatedDate - 1)];
					c.Currency = (reader.IsDBNull(((int)AfiColumn.Currency - 1)))?null:(System.String)reader[((int)AfiColumn.Currency - 1)];
					c.Status = (reader.IsDBNull(((int)AfiColumn.Status - 1)))?null:(System.String)reader[((int)AfiColumn.Status - 1)];
					c.Pam = (reader.IsDBNull(((int)AfiColumn.Pam - 1)))?null:(System.String)reader[((int)AfiColumn.Pam - 1)];
					c.EntityTrackingKey = key;
					c.AcceptChanges();
					c.SuppressEntityEvents = false;
				}
				rows.Add(c);
			}
		return rows;
		}		
		/// <summary>
		/// Refreshes the <see cref="EAdvice.Entities.Afi"/> object from the <see cref="IDataReader"/>.
		/// </summary>
		/// <param name="reader">The <see cref="IDataReader"/> to read from.</param>
		/// <param name="entity">The <see cref="EAdvice.Entities.Afi"/> object to refresh.</param>
		public static void RefreshEntity(IDataReader reader, EAdvice.Entities.Afi entity)
		{
			if (!reader.Read()) return;
			
			entity.AfiCode = (System.String)reader[((int)AfiColumn.AfiCode - 1)];
			entity.OriginalAfiCode = (System.String)reader["AFICode"];
			entity.ClientName = (System.String)reader[((int)AfiColumn.ClientName - 1)];
			entity.ClientAddress1 = (reader.IsDBNull(((int)AfiColumn.ClientAddress1 - 1)))?null:(System.String)reader[((int)AfiColumn.ClientAddress1 - 1)];
			entity.ClientAddress2 = (reader.IsDBNull(((int)AfiColumn.ClientAddress2 - 1)))?null:(System.String)reader[((int)AfiColumn.ClientAddress2 - 1)];
			entity.ClientAddress3 = (reader.IsDBNull(((int)AfiColumn.ClientAddress3 - 1)))?null:(System.String)reader[((int)AfiColumn.ClientAddress3 - 1)];
			entity.ClientTaxCode = (reader.IsDBNull(((int)AfiColumn.ClientTaxCode - 1)))?null:(System.String)reader[((int)AfiColumn.ClientTaxCode - 1)];
			entity.CreatedBy = (reader.IsDBNull(((int)AfiColumn.CreatedBy - 1)))?null:(System.String)reader[((int)AfiColumn.CreatedBy - 1)];
			entity.CreatedDate = (System.DateTime)reader[((int)AfiColumn.CreatedDate - 1)];
			entity.Currency = (reader.IsDBNull(((int)AfiColumn.Currency - 1)))?null:(System.String)reader[((int)AfiColumn.Currency - 1)];
			entity.Status = (reader.IsDBNull(((int)AfiColumn.Status - 1)))?null:(System.String)reader[((int)AfiColumn.Status - 1)];
			entity.Pam = (reader.IsDBNull(((int)AfiColumn.Pam - 1)))?null:(System.String)reader[((int)AfiColumn.Pam - 1)];
			entity.AcceptChanges();
		}
		
		/// <summary>
		/// Refreshes the <see cref="EAdvice.Entities.Afi"/> object from the <see cref="DataSet"/>.
		/// </summary>
		/// <param name="dataSet">The <see cref="DataSet"/> to read from.</param>
		/// <param name="entity">The <see cref="EAdvice.Entities.Afi"/> object.</param>
		public static void RefreshEntity(DataSet dataSet, EAdvice.Entities.Afi entity)
		{
			DataRow dataRow = dataSet.Tables[0].Rows[0];
			
			entity.AfiCode = (System.String)dataRow["AFICode"];
			entity.OriginalAfiCode = (System.String)dataRow["AFICode"];
			entity.ClientName = (System.String)dataRow["ClientName"];
			entity.ClientAddress1 = Convert.IsDBNull(dataRow["ClientAddress1"]) ? null : (System.String)dataRow["ClientAddress1"];
			entity.ClientAddress2 = Convert.IsDBNull(dataRow["ClientAddress2"]) ? null : (System.String)dataRow["ClientAddress2"];
			entity.ClientAddress3 = Convert.IsDBNull(dataRow["ClientAddress3"]) ? null : (System.String)dataRow["ClientAddress3"];
			entity.ClientTaxCode = Convert.IsDBNull(dataRow["ClientTaxCode"]) ? null : (System.String)dataRow["ClientTaxCode"];
			entity.CreatedBy = Convert.IsDBNull(dataRow["CreatedBy"]) ? null : (System.String)dataRow["CreatedBy"];
			entity.CreatedDate = (System.DateTime)dataRow["CreatedDate"];
			entity.Currency = Convert.IsDBNull(dataRow["Currency"]) ? null : (System.String)dataRow["Currency"];
			entity.Status = Convert.IsDBNull(dataRow["Status"]) ? null : (System.String)dataRow["Status"];
			entity.Pam = Convert.IsDBNull(dataRow["PAM"]) ? null : (System.String)dataRow["PAM"];
			entity.AcceptChanges();
		}
		#endregion 
		
		#region DeepLoad Methods
		/// <summary>
		/// Deep Loads the <see cref="IEntity"/> object with criteria based of the child 
		/// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>.
		/// </summary>
		/// <remarks>
		/// Use this method with caution as it is possible to DeepLoad with Recursion and traverse an entire object graph.
		/// </remarks>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="entity">The <see cref="EAdvice.Entities.Afi"/> object to load.</param>
		/// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param>
		/// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param>
		/// <param name="childTypes">EAdvice.Entities.Afi Property Collection Type Array To Include or Exclude from Load</param>
		/// <param name="innerList">A collection of child types for easy access.</param>
	    /// <exception cref="ArgumentNullException">entity or childTypes is null.</exception>
	    /// <exception cref="ArgumentException">deepLoadType has invalid value.</exception>
		public override void DeepLoad(TransactionManager transactionManager, EAdvice.Entities.Afi entity, bool deep, DeepLoadType deepLoadType, System.Type[] childTypes, DeepSession innerList)
		{
			if(entity == null)
				return;

			#region CreatedBySource	
			if (CanDeepLoad(entity, "WebUser|CreatedBySource", deepLoadType, innerList) 
				&& entity.CreatedBySource == null)
			{
				object[] pkItems = new object[1];
				pkItems[0] = (entity.CreatedBy ?? string.Empty);
				WebUser tmpEntity = EntityManager.LocateEntity<WebUser>(EntityLocator.ConstructKeyFromPkItems(typeof(WebUser), pkItems), DataRepository.Provider.EnableEntityTracking);
				if (tmpEntity != null)
					entity.CreatedBySource = tmpEntity;
				else
					entity.CreatedBySource = DataRepository.WebUserProvider.GetByUserId(transactionManager, (entity.CreatedBy ?? string.Empty));		
				
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'CreatedBySource' loaded. key " + entity.EntityTrackingKey);
				#endif 
				
				if (deep && entity.CreatedBySource != null)
				{
					innerList.SkipChildren = true;
					DataRepository.WebUserProvider.DeepLoad(transactionManager, entity.CreatedBySource, deep, deepLoadType, childTypes, innerList);
					innerList.SkipChildren = false;
				}
					
			}
			#endregion CreatedBySource
			
			//used to hold DeepLoad method delegates and fire after all the local children have been loaded.
			Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>();
			// Deep load child collections  - Call GetByAfiCode methods when available
			
			#region AttachmentCollection
			//Relationship Type One : Many
			if (CanDeepLoad(entity, "List<Attachment>|AttachmentCollection", deepLoadType, innerList)) 
			{
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'AttachmentCollection' loaded. key " + entity.EntityTrackingKey);
				#endif 

				entity.AttachmentCollection = DataRepository.AttachmentProvider.GetByAfiCode(transactionManager, entity.AfiCode);

				if (deep && entity.AttachmentCollection.Count > 0)
				{
					deepHandles.Add("AttachmentCollection",
						new KeyValuePair<Delegate, object>((DeepLoadHandle<Attachment>) DataRepository.AttachmentProvider.DeepLoad,
						new object[] { transactionManager, entity.AttachmentCollection, deep, deepLoadType, childTypes, innerList }
					));
				}
			}		
			#endregion 
			
			
			#region AfiDetailCollection
			//Relationship Type One : Many
			if (CanDeepLoad(entity, "List<AfiDetail>|AfiDetailCollection", deepLoadType, innerList)) 
			{
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'AfiDetailCollection' loaded. key " + entity.EntityTrackingKey);
				#endif 

				entity.AfiDetailCollection = DataRepository.AfiDetailProvider.GetByAfiCode(transactionManager, entity.AfiCode);

				if (deep && entity.AfiDetailCollection.Count > 0)
				{
					deepHandles.Add("AfiDetailCollection",
						new KeyValuePair<Delegate, object>((DeepLoadHandle<AfiDetail>) DataRepository.AfiDetailProvider.DeepLoad,
						new object[] { transactionManager, entity.AfiDetailCollection, deep, deepLoadType, childTypes, innerList }
					));
				}
			}		
			#endregion 
			
			
			//Fire all DeepLoad Items
			foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values)
		    {
                pair.Key.DynamicInvoke((object[])pair.Value);
		    }
			deepHandles = null;
		}
		
		#endregion 
		
		#region DeepSave Methods

		/// <summary>
		/// Deep Save the entire object graph of the EAdvice.Entities.Afi object with criteria based of the child 
		/// Type property array and DeepSaveType.
		/// </summary>
		/// <param name="transactionManager">The transaction manager.</param>
		/// <param name="entity">EAdvice.Entities.Afi instance</param>
		/// <param name="deepSaveType">DeepSaveType Enumeration to Include/Exclude object property collections from Save.</param>
		/// <param name="childTypes">EAdvice.Entities.Afi Property Collection Type Array To Include or Exclude from Save</param>
		/// <param name="innerList">A Hashtable of child types for easy access.</param>
		public override bool DeepSave(TransactionManager transactionManager, EAdvice.Entities.Afi entity, DeepSaveType deepSaveType, System.Type[] childTypes, DeepSession innerList)
		{	
			if (entity == null)
				return false;
							
			#region Composite Parent Properties
			//Save Source Composite Properties, however, don't call deep save on them.  
			//So they only get saved a single level deep.
			
			#region CreatedBySource
			if (CanDeepSave(entity, "WebUser|CreatedBySource", deepSaveType, innerList) 
				&& entity.CreatedBySource != null)
			{
				DataRepository.WebUserProvider.Save(transactionManager, entity.CreatedBySource);
				entity.CreatedBy = entity.CreatedBySource.UserId;
			}
			#endregion 
			#endregion Composite Parent Properties

			// Save Root Entity through Provider
			if (!entity.IsDeleted)
				this.Save(transactionManager, entity);
			
			//used to hold DeepSave method delegates and fire after all the local children have been saved.
			Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>();
	
			#region List<Attachment>
				if (CanDeepSave(entity.AttachmentCollection, "List<Attachment>|AttachmentCollection", deepSaveType, innerList)) 
				{	
					// update each child parent id with the real parent id (mostly used on insert)
					foreach(Attachment child in entity.AttachmentCollection)
					{
						if(child.AfiCodeSource != null)
						{
							child.AfiCode = child.AfiCodeSource.AfiCode;
						}
						else
						{
							child.AfiCode = entity.AfiCode;
						}

					}

					if (entity.AttachmentCollection.Count > 0 || entity.AttachmentCollection.DeletedItems.Count > 0)
					{
						//DataRepository.AttachmentProvider.Save(transactionManager, entity.AttachmentCollection);
						
						deepHandles.Add("AttachmentCollection",
						new KeyValuePair<Delegate, object>((DeepSaveHandle< Attachment >) DataRepository.AttachmentProvider.DeepSave,
							new object[] { transactionManager, entity.AttachmentCollection, deepSaveType, childTypes, innerList }
						));
					}
				} 
			#endregion 
				
	
			#region List<AfiDetail>
				if (CanDeepSave(entity.AfiDetailCollection, "List<AfiDetail>|AfiDetailCollection", deepSaveType, innerList)) 
				{	
					// update each child parent id with the real parent id (mostly used on insert)
					foreach(AfiDetail child in entity.AfiDetailCollection)
					{
						if(child.AfiCodeSource != null)
						{
							child.AfiCode = child.AfiCodeSource.AfiCode;
						}
						else
						{
							child.AfiCode = entity.AfiCode;
						}

					}

					if (entity.AfiDetailCollection.Count > 0 || entity.AfiDetailCollection.DeletedItems.Count > 0)
					{
						//DataRepository.AfiDetailProvider.Save(transactionManager, entity.AfiDetailCollection);
						
						deepHandles.Add("AfiDetailCollection",
						new KeyValuePair<Delegate, object>((DeepSaveHandle< AfiDetail >) DataRepository.AfiDetailProvider.DeepSave,
							new object[] { transactionManager, entity.AfiDetailCollection, deepSaveType, childTypes, innerList }
						));
					}
				} 
			#endregion 
				
			//Fire all DeepSave Items
			foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values)
		    {
                pair.Key.DynamicInvoke((object[])pair.Value);
		    }
			
			// Save Root Entity through Provider, if not already saved in delete mode
			if (entity.IsDeleted)
				this.Save(transactionManager, entity);
				

			deepHandles = null;
						
			return true;
		}
		#endregion
	} // end class
	
	#region AfiChildEntityTypes
	
	///<summary>
	/// Enumeration used to expose the different child entity types 
	/// for child properties in <c>EAdvice.Entities.Afi</c>
	///</summary>
	public enum AfiChildEntityTypes
	{
		
		///<summary>
		/// Composite Property for <c>WebUser</c> at CreatedBySource
		///</summary>
		[ChildEntityType(typeof(WebUser))]
		WebUser,
	
		///<summary>
		/// Collection of <c>Afi</c> as OneToMany for AttachmentCollection
		///</summary>
		[ChildEntityType(typeof(TList<Attachment>))]
		AttachmentCollection,

		///<summary>
		/// Collection of <c>Afi</c> as OneToMany for AfiDetailCollection
		///</summary>
		[ChildEntityType(typeof(TList<AfiDetail>))]
		AfiDetailCollection,
	}
	
	#endregion AfiChildEntityTypes
	
	#region AfiFilterBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="SqlFilterBuilder&lt;AfiColumn&gt;"/> class
	/// that is used exclusively with a <see cref="Afi"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class AfiFilterBuilder : SqlFilterBuilder<AfiColumn>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the AfiFilterBuilder class.
		/// </summary>
		public AfiFilterBuilder() : base() { }

		/// <summary>
		/// Initializes a new instance of the AfiFilterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		public AfiFilterBuilder(bool ignoreCase) : base(ignoreCase) { }

		/// <summary>
		/// Initializes a new instance of the AfiFilterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		/// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param>
		public AfiFilterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { }

		#endregion Constructors
	}

	#endregion AfiFilterBuilder
	
	#region AfiParameterBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="ParameterizedSqlFilterBuilder&lt;AfiColumn&gt;"/> class
	/// that is used exclusively with a <see cref="Afi"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class AfiParameterBuilder : ParameterizedSqlFilterBuilder<AfiColumn>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the AfiParameterBuilder class.
		/// </summary>
		public AfiParameterBuilder() : base() { }

		/// <summary>
		/// Initializes a new instance of the AfiParameterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		public AfiParameterBuilder(bool ignoreCase) : base(ignoreCase) { }

		/// <summary>
		/// Initializes a new instance of the AfiParameterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		/// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param>
		public AfiParameterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { }

		#endregion Constructors
	}

	#endregion AfiParameterBuilder
	
	#region AfiSortBuilder
    
    /// <summary>
    /// A strongly-typed instance of the <see cref="SqlSortBuilder&lt;AfiColumn&gt;"/> class
	/// that is used exclusively with a <see cref="Afi"/> object.
    /// </summary>
    [CLSCompliant(true)]
    public class AfiSortBuilder : SqlSortBuilder<AfiColumn>
    {
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the AfiSqlSortBuilder class.
		/// </summary>
		public AfiSortBuilder() : base() { }

		#endregion Constructors

    }    
    #endregion AfiSortBuilder
	
} // end namespace
